package com.wenjh.jdmzt.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;

import com.wenjh.jdmzt.AndroidKit;

/**
 * 图片处理类
 *
 * @author lijun
 *
 */
public class ImageUtil {
	/**
	 * 图片缩放
	 *
	 * @param bitmap
	 * @param w
	 *            宽度
	 * @param h
	 *            高度
	 * @return
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		if(bitmap == null) return null;
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidht = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidht, scaleHeight);
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newbmp;
	}

	/**
	 * 将Drawable转换为Bitmap对象
	 *
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmap(Drawable drawable) {
		int width = drawable.getIntrinsicWidth();
		int height = drawable.getIntrinsicHeight();
		Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
				.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
				: Bitmap.Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, width, height);
		drawable.draw(canvas);

		return bitmap;
	}

	public static Drawable Bitmap2Drawable(Bitmap b) {
		return new BitmapDrawable(b);
	}

	/**
	 * 为Bitmap图片添加圆角效果
	 *
	 * @param bitmap
	 *            原始图片
	 * @param roundPx
	 *            圆角大小
	 * @return
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {
		if(bitmap == null) return null;
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);
		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);
		return output;
	}

	/**
	 * 获得带倒影效果的图像
	 *
	 * @param bitmap
	 * @return
	 */
	public static Bitmap createReflectionImageWithOrigin(Bitmap bitmap) {
		final int reflectionGap = 4;
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);
		Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, height / 2,
				width, height / 2, matrix, false);
		Bitmap bitmapWithReflection = Bitmap.createBitmap(width,
				(height + height / 2), Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmapWithReflection);
		canvas.drawBitmap(bitmap, 0, 0, null);
		Paint deafalutPaint = new Paint();
		canvas.drawRect(0, height, width, height + reflectionGap, deafalutPaint);
		canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
		Paint paint = new Paint();
		LinearGradient shader = new LinearGradient(0, bitmap.getHeight(), 0,
				bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff,
				0x00ffffff, TileMode.CLAMP);
		paint.setShader(shader);
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));// Set the
																// Transfer mode
																// to be porter
																// duff and
																// destination
																// in
		canvas.drawRect(0, height, width, bitmapWithReflection.getHeight()
				+ reflectionGap, paint);// Draw a rectangle using the paint with
										// our linear gradient
		return bitmapWithReflection;
	}

	/**
	 * 将bitmap变成 字节码数组
	 *
	 * @param bitmap
	 * @return
	 */
	public static byte[] bitmap2Bytes(Bitmap bitmap) {
		if (bitmap == null)
			return null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	public static Bitmap getScaleBitmapOneStep(Context context, ContentResolver cr, final Uri uri, int maxPixels){
		InputStream is = null;
		Bitmap result = null;
		try {
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inJustDecodeBounds = true;
			opts.outWidth = maxPixels;
			opts.outHeight = maxPixels;
			is = cr.openInputStream(uri);
			BitmapFactory.decodeStream(is, null, opts);
			is.close();
			return result;
		} catch (Exception e) {
		}
		return result;
	}
	
	/**
	 * 获取指定大小的图片,将原图 等比例缩放, 返回
	 * @param context
	 * @param cr
	 * @param uri
	 * @param maxPixels 最大像素宽度/高度
	 * @return 返回位图
	 */
	public static Bitmap getScaleBitmap(Context context, ContentResolver cr, final Uri uri, int maxPixels) {
		Bitmap bitmap = null;
		InputStream is = null;
		Bitmap result = null;
		try {
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inJustDecodeBounds = true;
			is = cr.openInputStream(uri);
			BitmapFactory.decodeStream(is, null, opts);
			int srcWidth = opts.outWidth;
			int srcHeight = opts.outHeight;
			is.close();

			int maxlength = srcWidth >= srcHeight ? srcWidth : srcHeight;
			if(maxlength <= maxPixels){ //如果原图最大边小于 maxpixels 直接读取返回原图
				BitmapFactory.Options newOpts = new BitmapFactory.Options();
				is = cr.openInputStream(uri);
				result = BitmapFactory.decodeStream(is, null, newOpts);
				is.close();
				return result;
			}

			// 缩放比例
			float ratio = 0f;
			if (srcWidth >= srcHeight) {
				ratio = srcWidth / maxPixels;
			} else {
				ratio = srcHeight / maxPixels;
			}
			// 设置输出宽度、高度
			BitmapFactory.Options newOpts = new BitmapFactory.Options();
			int scaleSize = 1;
			if(ratio > 1){
				scaleSize = (int)ratio;
			}else{
				scaleSize = 1;
			}
			newOpts.inSampleSize = scaleSize;
			newOpts.inJustDecodeBounds = false;
			is = cr.openInputStream(uri);
			bitmap = BitmapFactory.decodeStream(is, null, newOpts);
			is.close();
			result = getScaledBitmapByPixel(bitmap, maxPixels, true);
			return result;
		} catch (Exception e) {
		}
		return result;
	}
	
	public static Bitmap getScaleBitmap(String path, int maxPixels) {
		File imageFile = new File(path);
		if(!imageFile.exists()) {
			return null;
		}
		
		Bitmap bitmap = null;
		InputStream is = null;
		Bitmap result = null;
		try {
			BitmapFactory.Options opts = new BitmapFactory.Options();
			opts.inJustDecodeBounds = true;
			is = new FileInputStream(imageFile);
			BitmapFactory.decodeStream(is, null, opts);
			is.close();
			int srcWidth = opts.outWidth;
			int srcHeight = opts.outHeight;

			int maxlength = srcWidth >= srcHeight ? srcWidth : srcHeight;
			if(maxlength <= maxPixels){ //如果原图最大边小于 maxpixels 直接读取返回原图
				BitmapFactory.Options newOpts = new BitmapFactory.Options();
				is = new FileInputStream(imageFile);
				result = BitmapFactory.decodeStream(is, null, newOpts);
				is.close();
				return result;
			}

			// 缩放比例
			float ratio = 0f;
			if (srcWidth >= srcHeight) {
				ratio = srcWidth / maxPixels;
			} else {
				ratio = srcHeight / maxPixels;
			}
			// 设置输出宽度、高度
			BitmapFactory.Options newOpts = new BitmapFactory.Options();
			int scaleSize = 1;
			if(ratio > 1){
				scaleSize = (int)ratio;
			}else{
				scaleSize = 1;
			}
			newOpts.inSampleSize = scaleSize;
			newOpts.inJustDecodeBounds = false;
			is = new FileInputStream(imageFile);
			bitmap = BitmapFactory.decodeStream(is, null, newOpts);
			is.close();
			result = getScaledBitmapByPixel(bitmap, maxPixels, true);
			return result;
		} catch (Exception e) {
			new Log4Android("ImageUtil").e(e);
		}
		return result;
	}
	
	/**
	 * 获取指定size的图片
	 * @param srcImg
	 * @param context
	 * @param maxPixels
	 * @return bitmap 处理后的结果
	 */
	public static Bitmap getScaledBitmapByPixel(Bitmap srcImg, int maxPixels, boolean isRecycleSrc){
		Bitmap result = null;
		int srcW = srcImg.getWidth();
		int srcH = srcImg.getHeight();
		int max = srcW > srcH ? srcW : srcH;
		if(max == maxPixels){
			return srcImg;
		}
		float radius = ((float)srcW ) / ((float)srcH);
		float scaledW;
		float scaledH;
		int BC_PHOTO_H = 0;
		if(srcW >= srcH){
			BC_PHOTO_H =  (int)(maxPixels / radius);
			scaledW = (float)maxPixels / srcW;
			scaledH = (float)BC_PHOTO_H / srcH;
		}else{
			BC_PHOTO_H =  (int)(maxPixels * radius);
			scaledW = (float)BC_PHOTO_H/ srcW;
			scaledH = (float)maxPixels / srcH;
		}
		Matrix matrix = new Matrix();
		matrix.postScale(scaledW, scaledH);
		result = Bitmap.createBitmap(srcImg, 0, 0, srcW, srcH, matrix, true); //抗锯齿、缩放处理
		if(srcImg != null && isRecycleSrc){
			srcImg.recycle();
			srcImg = null;
		}
		return result;
	}

	 /** 截取图片为正方形 **/
    public static Bitmap getSquaredBitmap(final Bitmap bitmap, final float ICON_LANGTH, boolean isRecycle) {
    	Bitmap bi = null;
    	if(bitmap != null) {
    		int w = bitmap.getWidth();
			int h = bitmap.getHeight();
			int nw = w > h ? h : w;
			int nh = nw;
			Matrix matrix = new Matrix();
			matrix.setScale(ICON_LANGTH / nw, ICON_LANGTH / nh);
			bi = Bitmap.createBitmap(bitmap, (w - nw) / 2, (h - nh) / 2, nw, nh, matrix, true);
			if(isRecycle){
				bitmap.recycle();
			}
    	}
    	return bi;
    }
    
    public static Bitmap getRoundBitmap(int pix, int color) {
    	int size = pix;
    	Bitmap bitmap = Bitmap.createBitmap(size,size,Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		Paint paint = new Paint();
		paint.setAntiAlias(true);
        paint.setColor(color);
        canvas.drawCircle(size/2f, size/2f, size/2f, paint);
		return bitmap;
    }

    public static Bitmap getRoundRectBitmap(int widthDip, int heightDip, int round, int color) {
    	int width = AndroidKit.getPixels(widthDip);
    	int height = AndroidKit.getPixels(heightDip);
    	round = AndroidKit.getPixels(round);

    	Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		Paint paint = new Paint();
		paint.setAntiAlias(true);
        paint.setColor(color);

        RectF rect = new RectF(0, 0, width, height);

		canvas.drawRoundRect(rect, round, round, paint);
		return bitmap;
    }


   
}
